package com.tarzan.gateway.repository;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarzan.gateway.mapper.RouteDefinitionMapper;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.tarzan.gateway.repository
 * @Title MyRouteDefinitionRepository
 * @Description TODO
 * @Author liujinshan
 * @CreateTime 2021/11/12 14:30
 */
@Component
public class MyRouteDefinitionRepository implements RouteDefinitionRepository {


    @Autowired
    private RouteDefinitionMapper routeDefinitionMapper;

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        List<RouteDefinition> routeDefinitions = new ArrayList<>();
        Wrapper<RouteDefinition> queryWrapper = new QueryWrapper<>();
        routeDefinitionMapper.selectList(queryWrapper).stream().
                forEach(routeDefinition ->
                        routeDefinitions.add(JSON.parseObject(routeDefinition.toString(),RouteDefinition.class)));
        return Flux.fromIterable(routeDefinitions);
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return route.flatMap(routeDefinition -> {
            routeDefinitionMapper.insert(routeDefinition);
            return Mono.empty();});
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return routeId.flatMap(id -> {
            if(null != routeDefinitionMapper.selectById(id)){
                routeDefinitionMapper.deleteById(id);
            }
            return Mono.defer(()->Mono.error(new NotFoundException("route definition is not found routeid:"+routeId)));
        });
    }
}
